<!-- Horizontal Form -->
 <div class="box box-info">
      <div class="box-header with-border">
        <h3 class="box-title">添加用户</h3>
        <h3 class="msg"></h3>
      </div>
      <!-- /.box-header -->
      <!-- form start -->
      <form class="form-horizontal">
        <div class="box-body">
         
          <div class="form-group">
            <label for="usernameId" class="col-sm-2 control-label">用户名</label>
            <div class="col-sm-10">
              <input type="text" name="username" class="form-control" id="usernameId">
            </div>
          </div>
          <div class="form-group" id="pwdDiv">
            <label for="passwordId" class="col-sm-2 control-label">密码</label>

            <div class="col-sm-10">
              <input type="password" name="password" class="form-control"  id="passwordId">
            </div>
          </div>
          
          <div class="form-group">
            <label for="deptId" class="col-sm-2 control-label">所属部门</label>
            <div class="col-sm-10">
              <input type="text" class="form-control load-sys-dept" readonly="readonly" id="deptId" placeholder="上级部门">
            </div>
          </div>
          
          <div class="form-group">
            <label for="emailId" class="col-sm-2 control-label">邮箱</label>
            <div class="col-sm-10">
              <input type="text" name="email" class="form-control"  id="emailId">
            </div>
          </div>
          <div class="form-group">
            <label for="phoneId" class="col-sm-2 control-label">手机号</label>
              <div class="col-sm-10">
              <input type="text" name="mobile" class="form-control"  id="phoneId">
            </div>
          </div>
          <div class="form-group">
            <label for="rolesId" class="col-sm-2 control-label">角色</label>
            <div class="col-sm-10" id="rolesId">
              
            </div>
          </div>
        </div>
        <!-- /.box-body -->
        <div class="box-footer">
          <button type="button" class="btn btn-default btn-cancel">Cancel</button>
          <button type="button" class="btn btn-info pull-right btn-save">Save</button>
        </div>
        <!-- /.box-footer -->
      </form>
     <div class="layui-layer layui-layer-page layui-layer-molv layer-anim" id="treeLayer" type="page" times="2" showtime="0" contype="object"
		style="z-index:59891016; width: 300px; height: 450px; top: 100px; left: 500px; display:none">
		<div class="layui-layer-title" style="cursor: move;">选择部门</div>
		<div class="layui-layer-content" style="height: 358px;">
			<div style="padding: 10px;" class="layui-layer-wrap">
				<ul id="zTreeId" class="ztree"></ul>    <!-- 动态加载树 -->
			</div>
		</div>
		<span class="layui-layer-setwin"> <a class="layui-layer-ico layui-layer-close layui-layer-close1 btn-cancel" ></a></span>
		<div class="layui-layer-btn layui-layer-btn-">
			<a class="layui-layer-btn0 btn-confirm">确定</a>
			<a class="layui-layer-btn1 btn-cancel">取消</a>
	     </div>
      </div>
    </div>
<script type="text/javascript" src="bower_components/ztree/jquery.ztree.all.min.js"></script>
<script type="text/javascript" src="bower_components/layer/layer.js"></script>
<script type="text/javascript">
 var zTree;
 //初始化zTree时会用到
 var setting = {
	data : {
		simpleData : {
			enable : true,
			idKey : "id",  //节点数据中保存唯一标识的属性名称
			pIdKey : "parentId",  //节点数据中保存其父节点唯一标识的属性名称
			rootPId : null  //根节点id
		}//json 格式javascript对象
	}
 }//json 格式的javascript对象
 $(document).ready(function(){
	 //页面加载完成以后加载角色信息并初始化页面
	  doLoadRoles();
	 //事件注册
	 $(".box-footer")
	 .on("click",".btn-cancel",doCancel)
	 .on("click",".btn-save",doSaveOrUpdate);
	 
	  $("#treeLayer")
	  .on("click",".btn-cancel",doHideTree)
	  .on("click",".btn-confirm",doConfirm);
	 
	 $(".form-horizontal")
	 .on("click",".load-sys-dept",doLoadZTreeNodes);
 });
 function doHideTree(){
	  $("#treeLayer").css("display","none");
 }
 //确定按钮
 function doConfirm(){
	  //1.获取选中的记录(id,name);
	  let selectedNodes=zTree.getSelectedNodes();
	  let node=selectedNodes[0];
	  //2.将id和name填写或绑定在具体对象上
	  $("#deptId").val(node.name);
	  $("#deptId").data("deptId",node.id)
	  //3.隐藏zTree对应的Div
	  doHideTree();
 }
 
 function doLoadZTreeNodes(){
	  let url=`${baseUrl}/dept/treeNodes`;
	  $("#treeLayer").css("display","block");
	  $.ajax({url:url,crossDomain:true,xhrFields:{withCredentials: true},success(result){
		  if(result.state==1){
			  zTree = $.fn.zTree.init($("#zTreeId"),setting,result.data);
		  }else{
			  alert(result.message);
		  }
	  }});
 }
 function doCancel(){
	$("#mainContentId").removeData("rowData");
	$("#mainContentId").load("/modules/sys/user_list.html");
 }
 function doSaveOrUpdate(){
	 let rowData=$("#mainContentId").data("rowData");
	 //1.获取表单数据
	 let data=doGetEditFormData();
	 if(rowData)data.id=rowData.id;
	 //2.发起异步请求
	 let url=`${baseUrl}/user/`;
	 let method=rowData?"put":"post";
	 $.ajax({
       method:method,
	   url:url,
       crossDomain:true,
       xhrFields:{withCredentials: true},
       data:JSON.stringify(data),
       contentType:"application/json",
       success(result){
         if(result.state==1){
           alert(result.message);
           doCancel();
         }else{
           alert(result.message);
         }
       }
   })
 }
 function doGetEditFormData(){
	 //获取用户输入的数据
	 let params={
	    username:$("#usernameId").val(),
	    password:$("#passwordId").val(),
	    email:$("#emailId").val(),
	    mobile:$("#phoneId").val(),
	    deptId:$("#deptId").data("deptId")
	 }
	 //获取选择的角色
	 let roleIds=new Array();
	 $("#rolesId input[name='roleId']")
	 .each(function(){
		 if($(this).prop("checked")){
			roleIds.push($(this).val());
		 }
	 });
	 params.roleIds=roleIds;
	 return params;
 }
 function doLoadRoles(){
	 let url=`${baseUrl}/role/checkRoles`;
	 $.ajax({url,crossDomain:true,xhrFields:{withCredentials: true},success(result){
		 if(result.state==1){
		  doInitPageRoles(result.data);
		  doInitFormData();//修改时
		 }else{
		  alert(result.message);
		 }
	 }})
 }
 function doInitFormData(){
     let data=$("#mainContentId").data("rowData");
     if(!data)return;
     $("#pwdDiv").remove();
	 console.log(data);
	 //初始化用户信息 
	 $("#usernameId").val(data.username);
	 $("#deptId").val(data.deptName);
	 $("#deptId").data("deptId",data.deptId);
	 $("#emailId").val(data.email);
	 $("#phoneId").val(data.mobile);
	 //初始化用户角色信息
	 let ids=data.roleIds;
	 ids.forEach((id)=>{
	  $(`#rolesId input[value=${id}]`)
	  .prop("checked",true);
	 })
 }
function doInitPageRoles(data){//List<CheckBox>
	 //1.获取角色要显示的位置对象
	 let div=$("#rolesId");
	 div.empty();
	 //2.迭代数据，将数据追加到div
	 let input=`<input type='checkbox' name='roleId' value='[id]'>[name]`
	 data.forEach(item=>{
		 //记住每次replace时都会产生一个新的字符串对象
		 var newInput=
		 input.replace("[id]",item.id)
		 .replace("[name]",item.name);
		 div.append(newInput)
	 });
 }
</script>
    
    
    
    
    
    
    